//
//  CountyList.m
//  LPlates.app
//
//  Created by Andreas Schwelling on 23.11.07.
//	http://www.andi.de/licenseplates/
//
//  Released under the GNU General Public License.
//  See LICENSE for details.
//
//  Use at your own risk.



#import "CountyList.h"

@implementation CountyList

- (id)initWithFrame:(struct CGRect)frame
{
	self = [super initWithFrame:frame];
	
	
	
	
	td = [MobileVehicleRegPlates sharedInstance];
	
	
	//Get full screen app rect
	struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
	rect.origin.x = rect.origin.y = 0.0f;
	
	navBar = [[UINavigationBar alloc] init];
	[navBar setFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, 45.0f)];
	[navBar showButtonsWithLeftTitle:@"Back" rightTitle:@"Search" leftBack:YES];
	[navBar setDelegate:self];
	[navBar enableAnimation];
	[navBar pushNavigationItem: [[UINavigationItem alloc] initWithTitle: @"Codes"]];
	
	bottomNavBar = [[UINavigationBar alloc] init];
	[bottomNavBar setFrame:CGRectMake(rect.origin.x, 415.0f, rect.size.width, 45.0f)];
	[bottomNavBar showLeftButton:@"HowTo" withStyle:0 rightButton:@"About" withStyle:0];
	
	[bottomNavBar setDelegate:self];
	[bottomNavBar enableAnimation];
	
	
	progresstable = [[UITable alloc] initWithFrame: CGRectMake(0.0f, 0.0f, 320.0f, 415.0f)];//-45.0f)];
	
	uip = [[UIProgressIndicator alloc] initWithFrame:CGRectMake(150, 210, 20,20)];
	
	[uip setStyle:1];
	[progresstable addSubview:uip];
	
	
	
	if ([[td getCountry] isEqualToString:@"Germany"]) licflag = [UIImage applicationImageNamed:@"germanpl.png"];
	if ([[td getCountry] isEqualToString:@"Austria"]) licflag = [UIImage applicationImageNamed:@"austriapl.png"];
	if ([[td getCountry] isEqualToString:@"Poland"]) licflag = [UIImage applicationImageNamed:@"polandpl.png"];
	if ([[td getCountry] isEqualToString:@"Czech Republic"]) licflag = [UIImage applicationImageNamed:@"czpl.png"];
	if ([[td getCountry] isEqualToString:@"Slovakia"]) licflag = [UIImage applicationImageNamed:@"skpl.png"];
	if ([[td getCountry] isEqualToString:@"Switzerland"]) licflag = [UIImage applicationImageNamed:@"swisspl.png"];
	if ([[td getCountry] isEqualToString:@"Norway"]) licflag = [UIImage applicationImageNamed:@"norwegianpl.png"];
	if ([[td getCountry] isEqualToString:@"Italy"]) licflag = [UIImage applicationImageNamed:@"italianpl.png"];
	
	//depricon 	= [UIImage applicationImageNamed:@"deprecated.png"];
	//
	
	[self addSubview:progresstable];
	[self addSubview:navBar];
	[self addSubview:bottomNavBar];
	[navBar addSubview:uip];
	[uip startAnimation];
	
	[NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(buildTable:) userInfo:nil repeats:NO];
	return self;
}

// Build the Table
- (void)buildTable:(id)param
{
	struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
	rect.origin.x = rect.origin.y = 0.0f;
	
	sectionList = [[UISectionList alloc] initWithFrame:CGRectMake(0.0f, 45.0f, 320.0f, 415.0f-45.0f) showSectionIndex:YES];
	[sectionList setDataSource:self];
	[sectionList reloadData];
	[self addSubview:sectionList];
	
	table = [sectionList table];
	[table setShouldHideHeaderInShortLists:NO];
	UITableColumn * packageColumn = [[UITableColumn alloc] initWithTitle:@"Title" identifier:@"title" width:320.0f];
	
	[table addTableColumn:packageColumn];
	[table setSeparatorStyle:1];
	[table setRowHeight:48.0f];
	[table setDelegate:self];
	[table setAllowsReordering:YES];
	
	
	
	
	[_tableCells release];
	_tableCells = [[NSMutableArray alloc] init];
	
	[_tableHeaders release];
	_tableHeaders = [[NSMutableArray alloc] init];
	
	countiesarr =  [[NSMutableArray alloc] init];
	deprcounties = [[NSMutableArray alloc] init];
	
	NSDictionary *dict =  [NSDictionary dictionaryWithContentsOfFile: @"/Applications/LPlates.app/default.plist"];
	
	NSArray *keys,*keys1;
	int k,j, count,count1;
	id key, value,  value1;
	
	keys = [dict allKeys];
	count = [keys count];
	
	int countycount = 0;
	
	for (j = 0; j < count; j++)
	  {
		  key = [keys objectAtIndex: j];
		  value = [dict objectForKey: key];
		  
		  keys1 = [value allKeys];
		  count1 = [keys1 count];
		  
		  
		  
		  NSDictionary *inner = [dict objectForKey: @"Countries"];
		  NSDictionary *inner1 = [inner objectForKey: [td getCountry]];
		  //NSLog (@"Key: %@ ", [inner1 allKeys] );
		  
		  
		  NSEnumerator *keyenum = [inner1 keyEnumerator];
		  [countiessorter release];
		  countiessorter = [[NSMutableArray alloc] init];
		  while ((key = [keyenum nextObject])) {
			  [countiessorter addObject: key];
		  }
		  
		  [countiessorter sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
		  
		  
		  id key;
		  int z = 0;
		  for(z=0;z<[countiessorter count];z++) {
			  //NSLog(@"%@",[countiessorter objectAtIndex:z]);
			  
			  // Each "header cell" here is a dictionary with two keys:
			  // title points to a NSSTring of what we want the header to say
			  // beginRow is a NSNumber integer that dictates which row this header will come before
			  NSMutableDictionary* cellDict = [[NSMutableDictionary alloc] initWithCapacity:2];
			  [cellDict setObject:[countiessorter objectAtIndex:z] forKey:@"title"];
			  [cellDict setObject:[[NSNumber alloc] initWithInt: countycount] forKey:@"beginRow"];
			  
			  [_tableHeaders addObject: cellDict];
			  
			  
			  NSDictionary *inner2 = [inner1 objectForKey:[countiessorter objectAtIndex:z]];
			  NSEnumerator *keyenum1 = [inner2 keyEnumerator];
			  id key1;
			  while ((key1 = [keyenum1 nextObject])) {
				  //		NSLog(@"%@ : %@", key1, [inner2 objectForKey:key1]);
				  NSDictionary *innerdic3 = [inner2 objectForKey:key1];
				  if ([innerdic3 objectForKey:@"depr"]) { continue; [deprcounties addObject:key1]; }
				  [countiesarr addObject:key1];
				  countycount++;
				  
			  }
			  
			  [countiesarr sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
			  int i = 0;
			  for (i = 0;i < [countiesarr count];i++) {
				  UIImageAndTextTableCell* cell = [[UIImageAndTextTableCell alloc] init];
				  [cell setTitle: [countiesarr objectAtIndex:i]];
				  [cell setDisclosureStyle:2];
				  if ([deprcounties containsObject:[countiesarr objectAtIndex:i]]) { 
					  //
					  
					  UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(260.0f, 12.0f, 32.0f, 22.0f)];
					  [img setImage:depricon];
					  [cell setAlpha:0.65f];
					  [cell addSubview:img];
					  [img release];	
				  }
				  
				  if (licflag) [cell setImage:licflag];
				  
				  [cell setShowDisclosure:NO animated:YES];
				  [_tableCells addObject: cell]; 
				  [cell release];
			  }
			  
			  [countiesarr release];
			  countiesarr =  [[NSMutableArray alloc] init];
			  [cellDict release];
			  
		  }
		  //	[keys dealloc];
		  //	[keys1 dealloc];
		  
		  
		  [countiesarr release];
		  
		  [countiessorter release];
		  [deprcounties release];
		  //	[dict dealloc];
	  }
	
	
	
	
	//	cellDict = [[NSMutableDictionary alloc] initWithCapacity:2];
	//[cellDict setObject:@"B" forKey:@"title"];
	//[cellDict setObject:[[NSNumber alloc] initWithInt:10] forKey:@"beginRow"];
	
	//[_tableHeaders addObject: cellDict];
	
	//Refresh the fileview table
	[sectionList reloadData];
	
	[sectionList setAlpha:0.0f];
	[self addSubview:sectionList];
	UIAlphaAnimation* alpha = [[UIAlphaAnimation alloc] initWithTarget: sectionList];
	[alpha setStartAlpha: 0.0f];
	[alpha setEndAlpha: 1.0f];
	[[[UIAnimator alloc] init] addAnimation:alpha withDuration:.8 start:YES];
	UIAlphaAnimation* alpha1 = [[UIAlphaAnimation alloc] initWithTarget: uip];
	[alpha1 setStartAlpha: 1.0f];
	[alpha1 setEndAlpha: 0.0f];
	[[[UIAnimator alloc] init] addAnimation:alpha1 withDuration:.5 start:YES];
	[alpha release];
	[alpha1 release];
	
	
}

- (void) dealloc
{
	[table release];
	[_tableHeaders release];
	[_tableCells release];
	[progresstable release];
	//	//[sectionList release];
	[navBar release];
	[bottomNavBar release];
	[uip release];
	//	[licflag release];
	[super dealloc];
	
}

- (void)setDelegate: (id)delegate
{
    _delegate = delegate;
}

#pragma mark ----------Delegate Methods-----------

- (void)navigationBar:(UINavigationBar*)bar buttonClicked:(int)button
{
	if (bar == bottomNavBar) {
		if (button == 1) [_delegate showWhatsSheet];
		if (button == 0) [_delegate showAboutSheet];
		
	} else
	  {
		  if (button == 1) [_delegate hideCountyView];
		  if (button == 0) [_delegate showSearchView];
	  } 
	
}



- (int)numberOfSectionsInSectionList:(UISectionList *)aSectionList {
	return [_tableHeaders count];
}

- (NSString *)sectionList:(UISectionList *)aSectionList titleForSection:(int)row {	
	return [[_tableHeaders objectAtIndex:row] objectForKey:@"title"];
}       

- (int)sectionList:(UISectionList *)aSectionList rowForSection:(int)row {
	// this is what determines the placement of the header
	return [[[_tableHeaders objectAtIndex:row] valueForKey:@"beginRow"] intValue];
}

- (UITableCell*) table: (UISectionTable*)table cellForRow: (int)row column: (int)col
{
	return [_tableCells objectAtIndex: row];
}

- (UITableCell*) table: (UISectionTable*)table cellForRow: (int)row column: (int)col
			   reusing: (BOOL) reusing
{
	//What does this message do?
    return nil;
}

- (int) numberOfRowsInTable: (UISectionTable*)table
{
	return [_tableCells count];
}

- (void) tableRowSelected: (NSNotification*) notification 
{
	//Get selected cell and filename
	UIImageAndTextTableCell* selectedCell = [_tableCells objectAtIndex: [table selectedRow]];
	[td setCounty:[selectedCell title]];
	
	[td setDescription:[selectedCell title]];
	[td setBeforeDetailView:self];
	[td showDetails:1];
	//Do stuff here...
}

@end